import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 考古加简洁解码器 - 模拟 RestTemplate 风格
 * 基于成功的 curl 配置实现
 */
public class KaoguRestDecoder {

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("🎯 考古加简洁解码器");
            System.out.println("用法: java KaoguRestDecoder <链接>");
            System.out
                    .println("示例: java KaoguRestDecoder https://www.kaogujia.com/darenDetails/darenOverview/9Q6Wd6vj");
            return;
        }

        String targetUrl = args[0];
        KaoguRestDecoder decoder = new KaoguRestDecoder();

        try {
            decoder.processUrl(targetUrl);
        } catch (Exception e) {
            System.out.println("❌ 处理出错: " + e.getMessage());
        }
    }

    /**
     * 处理URL
     */
    public void processUrl(String targetUrl) throws Exception {
        System.out.println("🚀 正在处理链接: " + targetUrl);

        // 提取作者ID
        String authorId = extractAuthorId(targetUrl);
        if (authorId == null) {
            System.out.println("❌ 无法从链接中提取作者ID");
            return;
        }

        System.out.println("📍 提取到作者ID: " + authorId);

        // 调用API
        String apiUrl = "https://service.kaogujia.com/api/author/detail/" + authorId;
        ApiResponse response = callApi(apiUrl);

        if (response.isSuccess()) {
            System.out.println("✅ API调用成功!");
            processData(response.getBody(), authorId);
        } else {
            System.out.println("❌ API调用失败: " + response.getStatusCode());
            System.out.println("错误信息: " + response.getErrorMessage());
        }
    }

    /**
     * 调用API - 模拟RestTemplate风格
     */
    private ApiResponse callApi(String apiUrl) {
        System.out.println("📡 正在调用API: " + apiUrl);

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(apiUrl).openConnection();

            // 设置基本参数
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);

            // 设置请求头（基于成功的curl配置）
            setHeaders(conn);

            int statusCode = conn.getResponseCode();
            System.out.println("📊 响应码: " + statusCode);

            if (statusCode == 200) {
                String responseBody = readResponse(conn);
                conn.disconnect();
                return new ApiResponse(true, statusCode, responseBody, null);
            } else {
                String errorBody = readErrorResponse(conn);
                conn.disconnect();
                return new ApiResponse(false, statusCode, null, errorBody);
            }

        } catch (Exception e) {
            return new ApiResponse(false, 0, null, e.getMessage());
        }
    }

    /**
     * 设置请求头
     */
    private void setHeaders(HttpURLConnection conn) {
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
        conn.setRequestProperty("Host", "service.kaogujia.com");
        conn.setRequestProperty("Origin", "https://www.kaogujia.com");
        conn.setRequestProperty("Referer", "https://www.kaogujia.com/");
        conn.setRequestProperty("Sec-Fetch-Dest", "empty");
        conn.setRequestProperty("Sec-Fetch-Mode", "cors");
        conn.setRequestProperty("Sec-Fetch-Site", "same-site");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36");
        conn.setRequestProperty("sec-ch-ua",
                "\"Chromium\";v=\"140\", \"Not=A?Brand\";v=\"24\", \"Google Chrome\";v=\"140\"");
        conn.setRequestProperty("sec-ch-ua-mobile", "?0");
        conn.setRequestProperty("sec-ch-ua-platform", "\"macOS\"");
        conn.setRequestProperty("version_code", "3.1"); // 关键头部！
        conn.setRequestProperty("Connection", "keep-alive");
    }

    /**
     * 提取作者ID
     */
    private String extractAuthorId(String url) {
        Pattern pattern = Pattern.compile("([A-Za-z0-9_-]+)/?$");
        Matcher matcher = pattern.matcher(url);
        return matcher.find() ? matcher.group(1) : null;
    }

    /**
     * 处理响应数据
     */
    private void processData(String response, String authorId) {
        System.out.println("🔓 开始解码数据...");

        // 查找data字段
        Pattern dataPattern = Pattern.compile("\"data\"\\s*:\\s*\"([^\"]+)\"");
        Matcher dataMatcher = dataPattern.matcher(response);

        if (dataMatcher.find()) {
            String encryptedData = dataMatcher.group(1);
            System.out.println("🔐 找到加密数据，长度: " + encryptedData.length());

            // 解密数据
            String decrypted = decrypt(encryptedData, authorId);

            if (decrypted != null && !decrypted.isEmpty()) {
                System.out.println("🎉 解密成功!");
                System.out.println("📄 解密结果:");
                System.out.println("=".repeat(80));
                System.out.println(decrypted);
                System.out.println("=".repeat(80));
            } else {
                System.out.println("❌ 解密失败");
            }
        } else {
            System.out.println("❌ 响应中未找到data字段");
            System.out.println("📄 响应内容: " + response.substring(0, Math.min(200, response.length())));
        }
    }

    /**
     * AES解密 - 使用正确的密钥生成算法
     */
    private String decrypt(String encryptedData, String authorId) {
        try {
            // 1. 生成密钥字符串：将API路径编码后重复3次
            String apiPath = "/api/author/detail/" + authorId;
            String encodedPath = Base64.getEncoder().encodeToString(apiPath.getBytes("UTF-8"));
            String keyString = encodedPath + encodedPath + encodedPath; // 重复3次

            // 2. 提取密钥和IV（使用正确的算法）
            String orgKey = keyString.substring(0, 16); // 前16位作为密钥
            String orgIv = keyString.substring(12, 28); // 12-28位作为IV

            System.out.println("🔑 API路径: " + apiPath);
            System.out.println("🔑 编码后路径: " + encodedPath);
            System.out.println("🔑 AES密钥: " + orgKey);
            System.out.println("🔑 AES IV: " + orgIv);

            // 3. 创建密钥和IV规范
            SecretKeySpec keySpec = new SecretKeySpec(orgKey.getBytes("UTF-8"), "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(orgIv.getBytes("UTF-8"));

            // 4. 初始化解密器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            // 5. Base64解码加密数据
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);

            // 6. 执行AES解密
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            // 7. 转换为字符串
            return new String(decryptedBytes, "UTF-8");

        } catch (Exception e) {
            System.out.println("❌ 解密异常: " + e.getMessage());
            return null;
        }
    }

    /**
     * 读取响应
     */
    private String readResponse(HttpURLConnection conn) throws IOException {
        InputStream inputStream = conn.getInputStream();
        String encoding = conn.getContentEncoding();

        if ("gzip".equalsIgnoreCase(encoding)) {
            inputStream = new java.util.zip.GZIPInputStream(inputStream);
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        reader.close();
        return response.toString();
    }

    /**
     * 读取错误响应
     */
    private String readErrorResponse(HttpURLConnection conn) throws IOException {
        InputStream errorStream = conn.getErrorStream();
        if (errorStream == null)
            return "无错误信息";

        BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream, "UTF-8"));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        reader.close();
        return response.toString();
    }

    /**
     * API响应封装类 - 模拟Spring的ResponseEntity
     */
    static class ApiResponse {
        private final boolean success;
        private final int statusCode;
        private final String body;
        private final String errorMessage;

        public ApiResponse(boolean success, int statusCode, String body, String errorMessage) {
            this.success = success;
            this.statusCode = statusCode;
            this.body = body;
            this.errorMessage = errorMessage;
        }

        public boolean isSuccess() {
            return success;
        }

        public int getStatusCode() {
            return statusCode;
        }

        public String getBody() {
            return body;
        }

        public String getErrorMessage() {
            return errorMessage;
        }
    }
}